import React, { Component } from 'react';
import SearchHeader from './SearchHeader'
import {searchData} from '../../api/search'
import {connect} from 'react-redux'
import SearchList from './SearchList'
import LoadMore from '../../component/LoadMore'
class Search extends Component {
    state={
        searchData:[],
        values:'',
        page:0,
        hasMore:true,
    }
    componentDidMount(){
        const city = this.props.city;
        const content = this.props.match.params.values.trim()
        this.setState({
            values:content
        })
        this.http(city,content,0)
    }
    http(city,content,page,type){
        if(type==="newSearch"){
            window.location.reload()
        }
        searchData(city,content,page).then(data=>{
            this.setState({
                searchData:[...this.state.searchData,...data.data],
                values:this.props.match.params.values.trim(),
                page:page + 1
            })
        })
    }
    loadMoreHandler = ()=>{
        const city = this.props.city;
        const content = this.props.match.params.values.trim()
        if(this.state.searchData.length>=24){
            this.setState({
                hasMore:false
            })
        }else{
        this.http(city,content,this.state.page)

        }
    }
    componentWillUpdate(newProps){
        const city = this.props.city;
        const content = newProps.match.params.values.trim()
        if(this.props.location.pathname != newProps.location.pathname){
            this.http(city,content,0,"newSearch")
        }
    }
    componentWillUnmount(){
        this.setState = ()=>{return}
    }
    render() {
        return (
            <div>
             <SearchHeader values={this.state.values}/>
             <SearchList searchData={this.state.searchData}/>
             {
                 this.state.hasMore?<LoadMore loadMoreHandler={this.loadMoreHandler}/>:<div>被你看光了</div>
             }
             
            </div>
        );
    }
}
const mapStateToProps = state=>{
   return{
    city:state.city.cityName
   }
}
export default connect(mapStateToProps)(Search);